import React, { useState, useEffect } from "react";
import { PayPalButton } from "react-paypal-button-v2";
import {
  Form,
  Button,
  Row,
  Col,
  Image,
  Card,
  ListGroup,
  Modal,
} from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import {
  getOrderDetails,
  payOrder,
  deliverOrder,
} from "../actions/orderActions";
import { Link } from "react-router-dom";
import Message from "../components/Message";
import axios from "axios";
import Loader from "../components/Loader";
import {
  ORDER_PAY_RESET,
  ORDER_DELIVER_RESET,
} from "../constants/orderConstants";
import { v4 as uuidv4 } from "uuid";

const OrderScreen = ({ match, history }) => {
  const orderId = match.params.id;
  const dispatch = useDispatch();
  //弹出框状态
  const [show, setShow] = useState(false);
  //支付二维码图片
  const [image, setImage] = useState("");
  //支付文本
  const [text, setText] = useState("请扫码");
  //PayPal SDK
  const [SDK, setSDK] = useState(false);

  //获取用户登录返回的值
  const userLogin = useSelector((state) => state.userLogin);
  const { userInfo } = userLogin;
  //获取订单详情返回的值
  const orderDetails = useSelector((state) => state.orderDetails);
  const { order, loading, error } = orderDetails;
  //获取更新订单支付状态返回的值
  const orderPay = useSelector((state) => state.orderPay);
  const { loading: loadingPay, success: successPay } = orderPay;
  //获取更新订单发货状态返回的值
  const orderDeliver = useSelector((state) => state.orderDeliver);
  const { loading: loadingDeliver, success: successDeliver } = orderDeliver;

  //计算价格
  if (!loading) {
    //保留小数点后两位
    const addDecimals = (num) => {
      return (Math.round(num * 100) / 100).toFixed(2);
    };
    //商品总价
    order.itemsPrice = addDecimals(
      order.orderItems.reduce((acc, item) => acc + item.price * item.qty, 0)
    );
  }

  //获取订单
  useEffect(() => {
    //动态创建PayPal script
    const addPayPalScript = async () => {
      const { data: clientId } = await axios.get("/api/config/paypal");
      const script = document.createElement("script");
      script.type = "text/javascript";
      script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}`;
      script.async = true;

      script.onload = () => {
        setSDK(true);
      };
      document.body.appendChild(script);
    };

    //如果没有登录
    if (!userInfo) {
      history.push("/login");
    }
    if (!order || order._id != orderId || successPay || successDeliver) {
      dispatch({ type: ORDER_PAY_RESET });
      dispatch({ type: ORDER_DELIVER_RESET });
      dispatch(getOrderDetails(orderId));
    } else if (!order.isPaid) {
      if (!window.paypal) {
        addPayPalScript();
      } else {
        setSDK(true);
      }
    }
  }, [dispatch, history, userInfo, order, orderId, successPay, successDeliver]);

  //设置定时器
  let timer;
  //创建开启和关闭弹出框的函数
  const handleClose = () => {
    clearTimeout(timer);
    setShow(false);
  };
  const handlePayment = () => {
    //获取微信返回的支付二维码图片
    // setImage("https://www.thenewstep.cn/pay/index.php?" + "pid=" + order._id);
    setImage("/images/wechat.jpg");
    setShow(true);

    // //定时器监听支付
    // let timer = setInterval(() => {
    //   //请求支付status
    //   axios.get("/status").then((res) => {
    //     if (res.data.status == 0) {
    //       setText("请扫码");
    //     } else if (res.data.status == 1) {
    //       setText("您已经完成了扫码支付");
    //     } else if (res.data.status == 2) {
    //       //创建支付结果对象
    //       const paymentResult = {
    //         id: uuidv4(),
    //         status: res.data.status,
    //         update_time: Date.now(),
    //         email_address: order.user.email,
    //       };
    //       //更新完成支付的订单
    //       dispatch(payOrder(orderId, paymentResult));
    //       setText("您已经支付成功，请等待发货");
    //       setShow(false);
    //       clearInterval(timer);
    //     }
    //   });
    // }, 1000);

    //模拟扫码付款
    timer = setTimeout(() => {
      //创建支付结果对象
      const paymentResult = {
        id: uuidv4(),
        status: "1",
        update_time: Date.now(),
        email_address: order.user.email,
      };
      //更新完成支付的订单
      dispatch(payOrder(orderId, paymentResult));
      // setText("您已经完成了扫码，请支付");
      setText("您已经完成了扫码支付");
      setShow(false);
    }, 5000);
  };

  //paypal支付按钮
  const successPaymentHandler = (paymentResult) => {
    console.log(paymentResult);
    dispatch(payOrder(orderId, paymentResult));
  };

  //点击发货btn
  const deliverHandler = () => {
    dispatch(deliverOrder(order));
  };

  return loading ? (
    <Loader></Loader>
  ) : error ? (
    <Message variant="danger">{error}</Message>
  ) : (
    <>
      <h1>订单号：{order._id}</h1>
      <Row>
        <Col md={8}>
          <ListGroup variant="flush">
            <ListGroup.Item>
              <h2>收货地址</h2>
              <p className="mb-2">
                <strong>收件人地址：</strong>
              </p>
              <p className="my-1">
                <strong>姓名：</strong>
                {order.user.name}
                <br></br>
                <strong>邮箱：</strong>
                <a href={`mailto:${order.user.email}`}>{order.user.email}</a>
              </p>
              <p className="my-1">
                {order.shippingAddress.province},{order.shippingAddress.city},
                {order.shippingAddress.address},
                {order.shippingAddress.postalCode}
              </p>
              {order.isDelivered ? (
                <Message variant="success">
                  发货时间：{order.deliveredAt}
                </Message>
              ) : (
                <Message>未发货</Message>
              )}
            </ListGroup.Item>
            <ListGroup.Item>
              <h2>支付方式</h2>
              <p className="my-1">
                <strong>支付方法：</strong>
                {order.paymentMethod}
              </p>
              {order.isPaid ? (
                <Message variant="success">支付时间：{order.paidAt}</Message>
              ) : (
                <Message>待支付</Message>
              )}
            </ListGroup.Item>
            <ListGroup.Item>
              <h2>产品订单</h2>
              {order.orderItems.length == 0 ? (
                <Message>购物车为空</Message>
              ) : (
                <ListGroup variant="flush">
                  {order.orderItems.map((item, index) => (
                    <ListGroup.Item key={index}>
                      <Row>
                        <Col md={1}>
                          <Image
                            src={item.image}
                            alt={item.name}
                            fluid
                            rounded
                          ></Image>
                        </Col>
                        <Col className="text-center">
                          <Link to={`/products/${item.product}`}>
                            {item.name}
                          </Link>
                        </Col>
                        <Col md={4} className="text-center">
                          ￥{item.price} × {item.qty}
                        </Col>
                        <Col className="text-center">
                          ￥{item.qty * item.price}
                        </Col>
                      </Row>
                    </ListGroup.Item>
                  ))}
                </ListGroup>
              )}
            </ListGroup.Item>
          </ListGroup>
        </Col>

        <Col md={4}>
          <Card>
            <ListGroup variant="flush">
              <ListGroup.Item>
                <h2>订单详情</h2>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>产品总价</Col>
                  <Col>￥{order.itemsPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>运费</Col>
                  <Col>￥{order.shippingPrice}</Col>
                </Row>
              </ListGroup.Item>
              <ListGroup.Item>
                <Row>
                  <Col>需付款</Col>
                  <Col>￥{order.totalPrice}</Col>
                </Row>
              </ListGroup.Item>
              {/* PayPal 支付按钮 */}
              {!order.isPaid && order.paymentMethod == "PayPal" && (
                <ListGroup.Item>
                  {loadingPay && <Loader></Loader>}
                  {!SDK ? (
                    <Loader></Loader>
                  ) : (
                    <PayPalButton
                      amount={order.totalPrice}
                      onSuccess={successPaymentHandler}
                    ></PayPalButton>
                  )}
                </ListGroup.Item>
              )}

              {/* 微信支付按钮 */}
              {!order.isPaid && order.paymentMethod == "微信" && (
                <ListGroup.Item>
                  <Button
                    type="button"
                    className="btn-block"
                    onClick={handlePayment}
                    disabled={order.orderItems.length == 0}
                  >
                    支付
                  </Button>
                  {/* 支付弹出框 */}
                  <Modal show={show} onHide={handleClose}>
                    <Modal.Header closeButton>
                      <Modal.Title>订单号:{order._id}</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                      <p>支付金额：¥{order.totalPrice}</p>
                      <p>支付方式：{order.paymentMethod}</p>
                      <Row>
                        <Col md={6} style={{ textAlign: "center" }}>
                          <Image src={image}></Image>
                          <p style={{ backgroundColor: "#08f", color: "#fff" }}>
                            {text}
                          </p>
                        </Col>
                        <Col>
                          <Image src="/images/saoyisao.jpg"></Image>
                        </Col>
                      </Row>
                    </Modal.Body>
                    <Modal.Footer>
                      <Button variant="primary" onClick={handleClose}>
                        关闭
                      </Button>
                    </Modal.Footer>
                  </Modal>
                </ListGroup.Item>
              )}

              {/* 发货btn */}
              {userInfo &&
                userInfo.isAdmin &&
                order.isPaid &&
                !order.isDelivered && (
                  <ListGroup.Item>
                    <Button
                      type="button"
                      className="btn-block"
                      onClick={deliverHandler}
                    >
                      发货
                    </Button>
                  </ListGroup.Item>
                )}
            </ListGroup>
          </Card>
        </Col>
      </Row>
    </>
  );
};

export default OrderScreen;
